<script setup>
import {onBeforeMount, ref, reactive} from "vue";
import {getAdminAllInfo, updatePwdAPI, updateUsernameAPI} from "@/api/manager.js";
import useAccountStore from "@/store/modules/AccountStore.js";
import {getDateTimeFormatNow} from "@/utils/DateUtils.js";
import {preview} from "vue3-image-preview";
import {Plus} from '@element-plus/icons-vue'
import {addPercentageInterval, INTERVAL_FIELD_NAME} from "@/utils/FileUtils.js";
import {FILE_URL_FIELD_NAME, fileUploadAPI, TIP_MSG_FIELD_NAME} from "@/api/file.js";
import {elErrorMessageTip, elSuccessMessageTip} from "@/utils/MessageTipUtils.js";
import {updateAvatarAPI} from "@/api/manager.js";
import {getManagerRole} from "../../../constants/ManagerRole.js";

const manager = ref({})
onBeforeMount(async () => {
  const res = await getAdminAllInfo()
  manager.value = res
  useAccountStore().saveManager(res)
})

const imgList = ref([])
const newAvatar = ref('')
const imgUpload = async (file, fileList) => {
  file = reactive(file)
  // fileList.value.push(file)
  fileList.value[0] = file
  file.status = 'uploading'
  // 文件上传进度计时器
  addPercentageInterval(file)
  // 文件上传
  const res = await fileUploadAPI(file.raw)
  if (res.status) {
    // 成功
    // 清除计时器
    clearInterval(file[INTERVAL_FIELD_NAME])
    elSuccessMessageTip(res[TIP_MSG_FIELD_NAME])
    file.status = 'success'
    file.percentage = 100
    file.url = res[FILE_URL_FIELD_NAME]
    newAvatar.value = file.url
  } else {
    // 失败
    // 清除计时器
    clearInterval(file[INTERVAL_FIELD_NAME])
    elErrorMessageTip(res[TIP_MSG_FIELD_NAME])
    file.status = 'fail'
    newAvatar.value = ''
  }
}
// 商品图片上传
const imgUploadHandler = (file) => {
  imgUpload(file, imgList)
}
const imgExceedHandler = (files) => {
  imgUpload({raw: files[0], percentage: 0}, imgList)
}
// 图片预览
const imgPreviewHandler = () => {
  preview({images: imgList.value, index: 0})
}
// 图片移除
const imgRemoveHandler = (index) => {
  newAvatar.value = ''
}
const updateAvatar = async () => {
  if (newAvatar.value.length <= 0) {
    elErrorMessageTip('请先上传头像')
    return
  }
  const res = await updateAvatarAPI(newAvatar.value)
  if (res) {
    newAvatar.value = ''
    imgList.value = []
    useAccountStore().saveManager(res)
    manager.value = useAccountStore().manager
  }
}

const newUsername = ref('')
const updateUsername = async () => {
  if (newUsername.value.length <= 0) {
    elErrorMessageTip('请先完成新用户名的输入')
    return
  }
  const res = await updateUsernameAPI(newUsername.value)
  if (res) {
    newUsername.value = ''
    useAccountStore().saveManager(res)
    manager.value = useAccountStore().manager
  }
}
const newPwd = ref('')
const confirmPwd = ref('')
const updatePwd = async () => {
  if (newPwd.value.length <= 0 || confirmPwd.value.length <= 0) {
    elErrorMessageTip('请先完成新密码的输入')
    return
  }
  if (newPwd.value !== confirmPwd.value) {
    elErrorMessageTip('两次输入的密码不一致')
    return
  }
  ElMessageBox.confirm(
      `是否确认修改密码`,
      '修改密码',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const res = await updatePwdAPI(newPwd.value)
    if (res) {
      newPwd.value = ''
      confirmPwd.value = ''
    }
  }).catch(() => {
  
  })
}
</script>

<template>
  <div class="my w-full pb-8 pt-4 flex flex-col justify-start items-center">
    <div class="glass-container backdrop-brightness-75 p-8 w-full flex flex-col items-center">
      <div
          class="text-gray-100 p-4 flex justify-start items-center cursor-pointer"
      >
        <div class="mr-4 w-20 h-20 rounded-full overflow-hidden">
          <!--<img class="w-full h-full object-cover" :src="manager?.avatar" alt="">-->
          <el-image
              preview-teleported
              class="mr-4 w-full h-full object-cover"
              :src="newAvatar.length > 0 ? newAvatar : manager?.avatar"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[newAvatar.length > 0 ? newAvatar : manager?.avatar]"
              fit="cover"
          />
        </div>
        <div>
          <div class="text-xl">{{ newUsername.length > 0 ? newUsername : manager?.username }}</div>
          <div class="mt-1 text-gray-300 text-xs">账号：{{ manager?.account }}</div>
        </div>
      </div>
      <div>邮箱：{{ manager?.mail }}</div>
      <div>角色：{{ getManagerRole(manager?.role) }}</div>
      <div>注册时间：{{ getDateTimeFormatNow(manager?.registerTime) }}</div>
      <!--<div class="w-96">-->
      <!--  <el-descriptions :column="1" direction="horizontal" border>-->
      <!--    <el-descriptions-item label="用户名">{{ manager?.username }}</el-descriptions-item>-->
      <!--    <el-descriptions-item label="账号">{{ manager?.account }}</el-descriptions-item>-->
      <!--    <el-descriptions-item label="头像" class="desc-item">-->
      <!--    </el-descriptions-item>-->
      <!--    <el-descriptions-item label="邮箱">{{ manager?.mail }}</el-descriptions-item>-->
      <!--    <el-descriptions-item label="注册时间">{{ getDateTimeFormatNow(manager?.registerTime) }}</el-descriptions-item>-->
      <!--  </el-descriptions>-->
      <!--</div>-->
    </div>
    <div class="glass-container mt-8 w-full p-4">
      <div class="flex justify-between">
        <div>更换头像</div>
        <div>
          <el-button type="primary" plain @click="updateAvatar">确认更换头像</el-button>
        </div>
      </div>
      <div class="p-2 flex-center">
        <el-upload
            v-model:file-list="imgList"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-remove="imgRemoveHandler"
            :on-exceed="imgExceedHandler"
            :on-change="imgUploadHandler"
            :on-preview="imgPreviewHandler"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </div>
    </div>
    <div class="glass-container mt-8 w-full p-4">
      <div class="flex justify-between items-center">
        <div class="flex-center justify-start items-center">
          <div class="mr-4">修改用户名</div>
          <div class="w-96">
            <el-input v-model="newUsername" placeholder="请输入新用户名" maxlength="20" show-word-limit
                      clearable></el-input>
          </div>
        </div>
        <div>
          <el-button @click="updateUsername" type="primary" plain>确认修改用户名</el-button>
        </div>
      </div>
    </div>
    <div class="glass-container mt-8 w-full p-4">
      <div class="flex justify-between items-center">
        <div>修改密码</div>
        <div>
          <el-button @click="updatePwd" type="primary" plain>确认修改密码</el-button>
        </div>
      </div>
      <div class="mt-4 flex-center">
        <div>
          <div class="mr-4">新密码</div>
          <div class="w-96">
            <el-input type="password" v-model="newPwd" placeholder="请输入新密码" maxlength="20" show-word-limit
                      clearable show-password></el-input>
          </div>
        </div>
      </div>
      <div class="mt-4 flex-center">
        <div>
          <div class="mr-4">确认密码</div>
          <div class="w-96">
            <el-input type="password" v-model="confirmPwd" placeholder="请确认密码" maxlength="20" show-word-limit
                      clearable show-password></el-input>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>